from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from app import db, app
from flask_sockets import Sockets
from flask import request,jsonify
from tools.Myjwt import myjwt
import time
# 注册蓝图
from application.views.users.user import user_blue
from application.views.users.sf_login import u_blue
from application.views.users.vip import vip_blue
from application.views.users.gethome import home_blue
from application.views.users.goods import goods_blue
app.register_blueprint(user_blue)
app.register_blueprint(u_blue, url_prefix='/user')
app.register_blueprint(vip_blue)
app.register_blueprint(home_blue)
app.register_blueprint(goods_blue)

# 生成管理工具对象
manager = Manager(app)
# 添加服务器运行指令
manager.add_command("runserver", Server(host='0.0.0.0', use_debugger=True))

# 数据库迁移
Migrate(app, db)
# 添加数据库的操作指令
manager.add_command("db", MigrateCommand)

# @app.before_request
# def before_request():
#     # 设置一个白名单
#     whitelist = ['/getImageCode', '/send', '/login']
#     url = request.path
#     if url not in whitelist:
#         # 判断当前访问的Url是否在白名单中，如果不在验证token
#         try:
#             token = request.headers['token']
#             # 获取token
#             # 调用jwt封装好的check_token对比
#             flag = myjwt.check(token)
#             if flag == True:
#                 # 如果通过验证过期时间
#                 payload = myjwt.jwt_decode(token)
#                 now = time.time()
#                 tnow = payload['data']['exp']
#                 if int(now) - int(tnow) > 3600:
#                     return jsonify({"code": 401, "msg": "token已过期"})
#             else:
#                 return jsonify({"code": 402, "msg": "token被篡改"})
#         except:
#             return jsonify({"code": 403, "msg": "没获取到token"})

import json
sockets = Sockets(app)
socketdict = {}
userlist = []


@sockets.route("/sockconn")
def sockconn(ws):
    # 接收前端传来的id
    id = request.args.get("id")
    if id != "kefu":
        userlist.append(id)
    socketdict[id] = ws
    print(socketdict)
    while not ws.closed:
        print("####")
        message = ws.receive()  # 接收到消息
        mes = json.loads(message)
        key = mes['send']
        if key != "conn":
            sendmes = json.dumps({"meslist": mes['mes'], "userlist": userlist})
            print(socketdict[key])
            socketdict[key].send(sendmes)
        else:
            ws.send(message)

# 如果是以此脚本作为主脚本程序，就执行
if __name__ == '__main__':
    # manager.run()
    app.run(port=8000)
    # from gevent import pywsgi
    # from geventwebsocket.handler import WebSocketHandler
    # server = pywsgi.WSGIServer(("localhost", 5000), app, handler_class=WebSocketHandler)
    # print("web server start ... ")
    # server.serve_forever()
